package com.example.test06thread.test.productandconsume;

/**
 * @Author: fxy
 * @Date: 2022/04/15/15:27
 * @Description:
 */
public class SynchronizedResolve {
    public static void main(String[] args) {
        PC pc = new PC();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    pc.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"P").start();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    pc.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
    }
}

class PC{
    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        if (number!=0){
            //等待
            this.wait();
        }
        //业务
        number++;
        System.out.println(Thread.currentThread().getName()+"===="+number);
        //通知
        this.notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        if (number==0){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"===="+number);
        this.notifyAll();
    }
}
